import {localSecretStorage} from "@/utils/ls.js";
import {defineStore} from "pinia";

const themeColors = {
    light: 'light',
    dark: 'dark',
    follow: 'follow'
}
// 设置 HTML 的 data-theme 属性
function applyTheme(theme) {
    const html = document.documentElement
    if (theme === 'dark') {
        html.setAttribute('data-theme', 'dark')
    } else {
        html.removeAttribute('data-theme') // 默认为 light
    }
}

export const useUIStore = defineStore("ui", {
    state: () => ({
        sidebarCollapsed: false, // 侧边栏是否折叠
        theme: themeColors.follow,
    }),
    getters: {
        getCurrentTheme() {
            if (this.theme === null || this.theme === themeColors.follow) {
                return window.matchMedia?.(`(prefers-color-scheme: ${themeColors.dark})`).matches ? themeColors.dark : themeColors.light;
            } else {
                return this.theme;
            }
        }
    },

    persist: {
        storage: localSecretStorage,
    },
    actions: {
        /**
         * 切换侧边栏折叠状态
         */
        toggleSidebar() {
            this.sidebarCollapsed = !this.sidebarCollapsed
        },

        /**
         * 设置主题
         * @param {string} theme - 'light' | 'dark' | 'follow'
         */
        setTheme(theme) {
            if (!Object.values(themeColors).includes(theme)) {
                console.warn(`Invalid theme: ${theme}`)
                return
            }
            this.theme = theme
            // 立即应用
            this.applyCurrentTheme()
        },

        /**
         * 应用当前计算出的主题到 DOM
         */
        applyCurrentTheme() {
            const theme = this.getCurrentTheme
            applyTheme(theme)
        },

        /**
         * 手动触发一次系统主题同步（可用于初始化或调试）
         */
        syncWithSystem() {
            if (this.theme === themeColors.follow) {
                this.applyCurrentTheme()
            }
        },
    }
});